/**
* 用户详情对话框（可用于添加和修改对话框）
*/
var CouponCardInfoDlg = {
    width: '650px',
    height: 'auto',
    currentLayerIndex: -1,
    cache: "",
    InfoData: {},
    userTableData: [],
    couponCardId: "",
    selectItemList: []
};

/**
 * 初始化新增弹出框
 */
CouponCardInfoDlg.init = function () {
    this.cache = $("#couponCardDialog").html();
    $("#couponCardDialog").html('');
};

/**
 * 清除数据
 */
CouponCardInfoDlg.clearData = function () {
    this.InfoData = {};
};

/**
 * 关闭此对话框
 */
CouponCardInfoDlg.close = function () {
    layer.close(this.currentLayerIndex);
};

/**
 * 新增打开模态框调用事件
 */
CouponCardInfoDlg.renderAdd = function () {
    //初始化icheck选中样式
    initICheck();
    this.selectItemList = [];
    this.userTableData = [];
    CouponCardInfoDlg.couponInfoInit();

    $("#useCondition").on("change",function () {
        var value =  $("#useCondition").val();
        if (value === "3") {
            //主动领取,显示数量、用户搜索
            $('#batchBtn').show();
            // $('#chooseUserBtn').hide();
            // $('#form_group_coupon_sum').show();
            $('#form_group_receive_user_ids').show();
        } else if (value === "4" || value === "5") {
            //专享优惠券，显示新老用户选项
            $('#batchBtn').hide();
            // $('#chooseUserBtn').show();
            // $('#form_group_coupon_sum').hide();
            $('#form_group_receive_user_ids').hide();
        } else {
            //注册、完善资料 隐藏数量，用户搜索
            // $('#form_group_coupon_sum').hide();
            $('#form_group_receive_user_ids').hide();
            $("#startDate").attr("disabled", "disabled");
            $("#endDate").attr("disabled", "disabled");
        }
    });
};

/**
 * 新增提交
 */
CouponCardInfoDlg.addSubmit = function (index) {
    this.clearData();
    this.InfoData = getFormJson("#frmMain");
    if(this.InfoData.couponSum==="") this.InfoData.couponSum=null;

    // 提交信息
    var ajax = new $ax(Feng.ctxPath+"/couponCard/save", function (data) {
        if (data.success){
            if (data.code ==1){
                Feng.success("添加成功!");
                layer.close(index);
                CouponCardTable.me.refresh();
            }else if(data.code ==2){
                Feng.error(data.msg);
            }else{
                CouponCardTable.me.refresh();
            }
        }else{
            Feng.error(data.msg);
        }
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.InfoData);
    ajax.start();
};

/**
 * 编辑
 */
CouponCardInfoDlg.load = function (id) {
    var ajax = new $ax(Feng.ctxPath+"/couponCard/getById", function(data){
        Feng.log("优惠券信息查询成功");
        if (data.success){
            var couponCard = data.obj.couponCard;
            var receiveUserList = data.obj.receiveUserList === null ? [] : data.obj.receiveUserList;

            for (var i in couponCard) {
                //判断Id与name是否相同
                if($("#"+i).attr("name")==i){
                    $("#" + i).val(couponCard[i]);
                }
            }
            CouponCardInfoDlg.couponInfoEditInit();
            //根据触发条件控制用户列表显隐
            var useCondition = couponCard.useCondition;
            if (useCondition === "3" || useCondition === "4" || useCondition === "5") {
                //主动领用、专享优惠券
                $('#batchBtn').show();
                // $('#chooseUserBtn').hide();
                $('#form_group_coupon_sum').show();
                $('#form_group_receive_user_ids').show();
            } else {
                //注册、完善资料 隐藏数量，用户搜索
                $('#form_group_coupon_sum').hide();
                $('#form_group_receive_user_ids').hide();
            }
            //加载用户列表数据
            for (var j = 0; j < receiveUserList.length; j++) {
                receiveUserList[j].isNewUser = "NO";
            }
            CouponCardInfoDlg.selectItemList = receiveUserList;
            CouponCardInfoDlg.userTableData = receiveUserList;
            CouponCardInfoDlg.refresh();
        }
    },function(data){
        Feng.error("加载信息失败!");
    });
    ajax.data={id:id};
    ajax.start();
};

CouponCardInfoDlg.couponInfoEditInit = function () {
    $("#useTypeId").attr("disabled", "disabled");
    $("#useCondition").attr("disabled", "disabled");
    $("#couponName").attr("readonly", "readonly");
    $("#couponSum").attr("readonly", "readonly");
    $("#conditionalAmount").attr("readonly", "readonly");
    $("#usefulTime").attr("readonly", "readonly");
    $("#discountAmount").attr("readonly", "readonly");
};

CouponCardInfoDlg.couponInfoInit = function () {
    $("#couponSum").val("0");
    $("#couponSum").removeAttr("readonly");
    $("#useTypeId").removeAttr("disabled");
    $("#useCondition").removeAttr("disabled");
    $("#couponName").removeAttr("readonly");
    $("#conditionalAmount").removeAttr("readonly");
    $("#usefulTime").removeAttr("readonly");
    $("#discountAmount").removeAttr("readonly");
    $("#startDate").removeAttr("disabled");
    $("#endDate").removeAttr("disabled");
};

/**
 * 提交修改
 */
CouponCardInfoDlg.editSubmit = function () {

    this.clearData();
    this.InfoData = getFormJson("#frmMain");
    if(this.InfoData.couponSum==="") this.InfoData.couponSum=null;

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/couponCard/update", function (data) {
        if (data) {
            Feng.success("修改成功!");
            CouponCardTable.me.refresh();
        } else {
            Feng.error("修改失败!");
        }
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.InfoData);
    ajax.start();
};

/**
 * 判断关联列表是否包含新选中用户
 * @param arr
 * @param obj
 * @returns {boolean}
 */
function contains(arr, obj) {
    var i = arr.length;
    while (i--) {
        if (arr[i].userId === obj.id) {
            return true;
        }
    }
    return false;
}

/**
 * 点击批量绑定按钮时，跳出批量绑定对话框
 * @returns
 */
function clickBatchBtn() {
    ReceiveUserBatchInfoDlg.clearData();
    var index = layer.open({
        type: 1,
        title: '选择领券用户',
        skin: 'layui-layer-lan', //加上边框
        area: [ReceiveUserBatchInfoDlg.width, ReceiveUserBatchInfoDlg.height],//宽高
        content: ReceiveUserBatchInfoDlg.cache,
        success: function (layero, index) {
            //层弹出成功后回调方法
            ReceiveUserBatchInfoDlg.renderAdd();
        },
        maxmin: true,
        scrollbar: false,
        btn: ['选中', '关闭'],
        btnAlign: 'r',  //默认值
        yes: function (index, layero) {
            ReceiveUserBatchInfoDlg.batchBindSubmit();
            //新选中的用户显示
            var arr = ReceiveUserBatchInfoDlg.selectData;
            for (item in arr) {
                if (contains(CouponCardInfoDlg.selectItemList, arr[item])) {
                    Feng.error("请不要重复选择用户");
                } else {
                    CouponCardInfoDlg.selectItemList.push({
                        userId: arr[item].id,
                        userName: arr[item].name,
                        userPhone: arr[item].phone,
                        couponState: "4",
                        couponItemId: "",
                        isNewUser: "YES"
                    })
                }
            }
            CouponCardInfoDlg.userTableData = CouponCardInfoDlg.selectItemList;
            CouponCardInfoDlg.refresh();
            layer.close(index); //如果设定了yes回调，需进行手工关闭
        }, btn2: function (index) {
            layer.close(index);
        },
        cancel: function (index, layero) {
            //右上角关闭按钮触发的回调
            layer.close(index);
        }
    });
    ReceiveUserBatchInfoDlg.currentLayerIndex = index;
}

/**
 * 刷新可领券用户列表
 */
CouponCardInfoDlg.refresh = function () {
    var outHtml = template("dataReceiveUserContentTmpl", this.userTableData);
    $("#userTableBody").html(outHtml);
};

/**
 * 删除领卷用户列表
 * @param couponItemId  优惠券明细ID
 * @param userId        用户ID
 * @param isNewUser     是否是新添加的用户
 */
CouponCardInfoDlg.deleteReceiveUser = function (couponItemId, userId, isNewUser) {
    if (isNewUser === 'YES') {
        //新添加的临时信息，未保存
        //删除列表显示数据
        this.userTableData.splice($.inArray(userId, this.userTableData), 1);
        //删除新加关联用户中的ID
        var newUserArr = ReceiveUserBatchInfoDlg.seItemArr;
        newUserArr.splice($.inArray(userId, newUserArr), 1);
        //去掉末尾逗号
        var userIds = newUserArr.join(",");
        $("#receiveUserIds").val(userIds);
        CouponCardInfoDlg.refresh();
    } else {
        //数据库中信息
        Feng.error("已保存数据无法删除!");

        /* var ajax = new $ax(Feng.ctxPath + "/couponCard/disqualifyOfReceiveCoupon", function (data) {
             if (data.success) {
                 Feng.success("修改成功!");
                 CouponCardInfoDlg.close();
             }else{
                 Feng.error(data.msg);
             }
         }, function (data) {
             Feng.error("修改失败!" + data.responseJSON.message + "!");
         });
         ajax.set({couponCardItemsId:couponItemId});
         ajax.start();*/
    }
};


